package org.headquarter;

import java.io.File;

import org.headquarter.business.NodeManager;
import org.headquarter.gui.Viewer;
import org.headquarter.object.Document;
import org.headquarter.object.Node;
import org.headquarter.object.Place;
import org.headquarter.object.Text;
import org.headquarter.object.UnicId;
import org.headquarter.persistance.FileSystemNodeRepository;
import org.headquarter.persistance.LoadError;
import org.headquarter.persistance.SaveError;
import org.headquarter.search.IndexError;
import org.headquarter.search.NodeSearcher;
import org.headquarter.search.SearchError;

public class HeadQuarter {
    NodeManager nm ;
    Viewer v;
    public HeadQuarter() throws LoadError, SaveError, IndexError{

	nm = new NodeManager();
	loadRepository(nm);
	nm.setNodeSearcher(new NodeSearcher("./index"));

	
	Place rootPlace = (Place)loadRoot();
	if(rootPlace==null){
	    rootPlace = new Place();
	    rootPlace.setUnicId(UnicId.ROOT);
	    rootPlace.setName(new Text("Root Place"));
	    nm.saveNode(rootPlace);
	}
	
	v= new Viewer(rootPlace);
	
    }

    private void loadRepository(NodeManager nm) {
	nm.setNodePersister(new FileSystemNodeRepository("./repository"));
    }

    public Node loadRoot() throws LoadError{
	return nm.getNode(UnicId.ROOT);
    }

    public void resetData() {
	File repo = new File("./repository");
	for(File file : repo.listFiles()){
	    file.delete();
	}
    }

    public void resetIndex() {
	File index = new File("./index");
	for(File file : index.listFiles()){
	    file.delete();
	}
    }


    public void addContent() throws SaveError, IndexError{




	Document doc = new Document();
	doc.setTitle(new Text("Plan de mariage"));
	doc.getTags().add("event");
	doc.getGroups().add("personal");

	nm.saveNode(doc);

	doc = new Document().setTitle(new Text("tenu mariage"));
	doc.getTags().add("event");
	doc.getGroups().add("personal");


	nm.saveNode(doc);






    }


    public void search() throws SearchError {

	nm.getNodeSearcher().findNode("tag:event");

	nm.getNodeSearcher().findNode("mariage");

	nm.getNodeSearcher().findNode("tag:event");




    }

    public void shutdown() throws IndexError{
	nm.shutdown();
    }



    public static void main(String[] args) {
	HeadQuarter hq;
	try {
	    hq = new HeadQuarter();
	    hq.resetIndex();
	} catch (LoadError e) {
	    e.printStackTrace();
	} catch (SaveError e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	} catch (IndexError e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}


    }
}
